<template>
	<view class="contain bg-color-f7">
		<view class="bg-color-w wrap-header">
			<view class="flex f-a-c f-j-c h-36 p-r f18-size f18-siz f-w-500">
				<view class="flex f-a-c padding-lr12 wrap-back" @click="back(1)">
					<image class="w-20" src="@/static/images/back.png" mode="widthFix"></image>
				</view>
				拍舌头测健康
			</view>
			<view class="flex f-j-c padding-tb10 margin-t8">
				<view class="flex f-c f-a-c f-j-c padding-lr20">
					<image class="w-34" src="@/static/images/step_1.png" mode="widthFix"></image>
					<view class="margin-t6">上传舌照</view>
					<view class="f12-size t-color-9 margin-t2">自然光下</view>
					<view class="f12-size t-color-9 margin-t2">拍摄舌面照片</view>
				</view>
				<view class="flex f-c f-a-c f-j-c padding-lr20">
					<image class="w-34" src="@/static/images/step_2.png" mode="widthFix"></image>
					<view class="margin-t6">快速检测</view>
					<view class="f12-size t-color-9 margin-t2">一分钟检测</view>
					<view class="f12-size t-color-9 margin-t2">身体状况</view>
				</view>
				<view class="flex f-c f-a-c f-j-c padding-lr20">
					<image class="w-34" src="@/static/images/step_3.png" mode="widthFix"></image>
					<view class="margin-t6">专业分析</view>
					<view class="f12-size t-color-9 margin-t2">智能分析</view>
					<view class="f12-size t-color-9 margin-t2">定制调理方案</view>
				</view>
			</view>
			
		</view>
		
		<view class="padding-lr20 margin-t12">
			<view class="f-w-500">请上传舌面、舌底、正脸三张照片</view>
			<view class="f12-size t-color-r margin-t2">要求拍摄清晰，方便检测</view>
		</view>
		
		<view class="padding-lr15 margin-t2">
			
			<view @click="uploadImg(0)" class="padding-12 b-radius-4 bg-color-fb margin-t10 p-r flex">
				<image class="num w-35" src="@/static/images/num_1.png" mode="widthFix"></image>
				<view class="flex flex-1 f-c f-a-c f-j-c">
					<view class="f16-size f-w-500">舌面</view>
					<image class="w-80 margin-t4" src="@/static/images/sl_1.png" mode="widthFix"></image>
				</view>
				<view class="bg-color-w flex f-a-c f-j-c p-r ">
					<image class="w-170" src="@/static/images/img_bg.png" mode="widthFix"></image>
					<view class="img-item flex f-a-c f-j-c bg-img" :style="imgArr[0] | bgimg()+''">
						<image class="w-60" src="@/static/images/img_bg1.png" mode="widthFix"></image>
					</view>
				</view>
			</view>
			
			<view @click="uploadImg(2)" class="padding-12 b-radius-4 bg-color-fb margin-t10 p-r flex">
				<image class="num w-35" src="@/static/images/num_2.png" mode="widthFix"></image>
				<view class="flex flex-1 f-c f-a-c f-j-c">
					<view class="f16-size f-w-500">舌底</view>
					<image class="w-80 margin-t4" src="@/static/images/sl_2.png" mode="widthFix"></image>
				</view>
				<view class="bg-color-w flex f-a-c f-j-c p-r">
					<image class="w-170" src="@/static/images/img_bg.png" mode="widthFix"></image>
					<view class="img-item flex f-a-c f-j-c bg-img" :style="imgArr[2] | bgimg()+''">
						<image class="w-60" src="@/static/images/img_bg1.png" mode="widthFix"></image>
					</view>
				</view>
			</view>
			
			<view  @click="uploadImg(1)" class="padding-12 b-radius-4 bg-color-fb margin-t10 p-r flex">
				<image class="num w-35" src="@/static/images/num_3.png" mode="widthFix"></image>
				<view class="flex flex-1 f-c f-a-c f-j-c">
					<view class="f16-size f-w-500">正脸</view>
					<image class="w-80 margin-t4" src="@/static/images/sl_3.png" mode="widthFix"></image>
				</view>
				<view class="bg-color-w flex f-a-c f-j-c p-r">
					<image class="w-170" src="@/static/images/img_bg.png" mode="widthFix"></image>
					<view class="img-item flex f-a-c f-j-c bg-img" :style="imgArr[1] | bgimg()+''">
						<image class="w-60" src="@/static/images/img_bg2.png" mode="widthFix"></image>
					</view>
				</view>
			</view>
			
			
		</view>
		
		<view class="padding-tb20"></view>
		<view class="padding-tb20"></view>
		<view class="wrap-btn bg-color-w">
			<!-- <view @click="getDetail()" class="bg-color-d flex f-a-c f-j-c h-50 b-radius-8 t-color-w f18-size ">查看示例报告</view> -->
			<view @click="getQs" style="margin-top: 10rpx;" :class="isCan ? 'bg-color-d' :'bg-color-e'" class="flex f-a-c f-j-c h-50 b-radius-8 t-color-w f18-size ">提交申请</view>
		</view>
	</view>
</template>
<style scoped>
	.wrap-btn {
		position: fixed;
		bottom: 0;
		width: 100%;
		padding: 20px 15px;
		z-index: 11;
	}
	.wrap-back {
		position: absolute;
		left: 0;
		height: 100%;
	}
	.wrap-header {
		border-radius: 0 0 10px 10px;
		box-shadow: 0px 1px 5px 0px rgba(193,193,193,0.3);
	}
	.img-item {
		position: absolute;
		inset: 0;
	}
	.num {
		position: absolute;
		top: 0;
		left:0;
	}
</style>
<script>
	const $ = require('@/utils/api.js');
	export default {
		components: {},
		data() {
			return {
				imgArr: ['','',''],
			};
		},
		onLoad: function(options) {
			this.handleWeChatCallback();
		},
		onShow() {
		},
		methods: {
			getDetail() {
				
			},
			onBridgeReady(data) {
				  var that = this
				  WeixinJSBridge.invoke('getBrandWCPayRequest', {
					  "appId": data.data.appId,     //公众号ID，由商户传入     
					  "timeStamp": data.data.timeStamp,     //时间戳，自1970年以来的秒数     
					  "nonceStr": data.data.nonceStr,      //随机串     
					  "package": data.data.package,
					  "signType": "MD5",     //微信签名方式：     
					  "paySign": data.data.paySign,
				  },
				  function(res) {
					  alert(123)
					  if (res.err_msg == "get_brand_wcpay_request:ok") {
						  // 使用以上方式判断前端返回,微信团队郑重提示：
						  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
						  that.pollPaymentResult();
					  }
				  });
			},
			async handleWeChatCallback() {
			  const urlParams = new URLSearchParams(window.location.search);
			  const code = urlParams.get('code');
			  if (code) {
			    try {
			      const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/login?code=${code}`);
			      const data = await response.json();
			      console.log(data.data.open_id);
			      if (data.data.open_id) {
					  localStorage.setItem('openid', data.data.id);
			        // this.saveOpenID(data.data.open_id);
			        // this.getAvailableTimes(data.data.open_id); // 获取可用次数和会员到期时间
			        // window.history.replaceState({}, document.title, window.location.pathname);
			      } else {
			        console.error('Failed to get openid from server');
			      }
			    } catch (error) {
			      console.error('Error during WeChat login:', error);
			    }
			  } else {
			    this.checkOpenID();
			  }
			},
			checkOpenID() {
			  const openid = localStorage.getItem('openid');
			  console.log(openid);
			  if (openid) {
			     // 获取可用次数和会员到期时间
			  } else {
			    this.weChatLogin();
			  }
			},
			weChatLogin() {
			  const appId = 'wxad67b499443b7a4b';
			  const redirectUri = encodeURIComponent(window.location.href);
			  const weChatAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base#wechat_redirect`;
			  window.location.href = weChatAuthUrl;
			},
			getQs() {
				if(!this.isCan){return}
				const self = this;
				uni.showLoading({
					title:'报告分析中…'
				})
				$.ajax({
					url: 'oneyuan/index/createReport',
					data: {
						scene: 1,
						tf_image: this.imgArr[0],//tf_image是舌头, ff_image是面部, tb_image是舌头下
						ff_image: this.imgArr[1],
						tb_image: this.imgArr[2],
					},
					method: 'POST',
					loadingText: '报告分析中…',
					showLoading: true,
					success(res) {
						uni.hideLoading();
						const data = res.data ? res.data : '';
						uni.setStorageSync('qs',data.inquiry_questions);
						self.go('/pages/index/qs?id='+data.session_id);
					},
					error(res) {
						console.log(res);
						$.$toast(res.msg);
						uni.hideLoading();
						self.len = 0;
					}
				})
			},
			uploadImg(index) {
				const self = this;
				$.uploadimg({
					success(res) {
						self.$set(self.imgArr,index,res);
						console.log(self.imgArr,'res')
					}
				})
			},
			async rechargeMembership() {
			  // 请求服务端获取微信支付参数
			  try {
			    const response = await fetch('https://data.bingdou.site/server/oneyuan/index/pay', {
			      method: 'POST',
			      headers: {
			        'Content-Type': 'application/json'
			      },
			      body: JSON.stringify({
			        open_id: localStorage.getItem('openid')
			      })
			    });
			    const data = await response.json();
					  this.orderNo = data.data.order_no;
					  
					  if (typeof WeixinJSBridge == "undefined") {
					      if (document.addEventListener) {
					          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
					      } else if (document.attachEvent) {
					          document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
					          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
					      }
					  } else {
					      this.onBridgeReady(data);
					  }
					} catch (error) {
					  console.error('请求支付参数时出错:', error);
					}
			},
			async pollPaymentResult() {
			  const pollInterval = 1000; // 轮询间隔时间（毫秒）
			  const maxAttempts = 20; // 最大轮询次数
			  let attempts = 0;
					const orderNo = this.orderNo;
			  const poll = async () => {
			    try {
			      const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/getOrderPayment?order_no=${orderNo}`);
			      const data = await response.json();
			      if (data.code === 0) {
			        // 支付成功
			        // alert('充值成功');
			        this.getAvailableTimes(localStorage.getItem('openid')); // 更新会员信息
			        return;
			      } else if (data.code === 1) {
			        // 支付进行中，继续轮询
			        if (attempts < maxAttempts) {
			          attempts++;
			          setTimeout(poll, pollInterval);
			        } else {
			          alert('支付结果查询超时');
			        }
			      } else {
			        // 支付失败
			        alert('支付失败');
			      }
			    } catch (error) {
			      console.error('查询支付结果时出错:', error);
			      alert('查询支付结果时出错');
			    }
			  };
			
			  poll();
			},
			init() {},
		},
		computed: {
			isCan() {
				const list = this.imgArr.filter(ele => ele != '');
				return list.length >= 3
			}
		},
		created() {
		},
		mounted() {},
		destroyed() {},
		onPullDownRefresh() {
		},
		onReachBottom() {
			
		}
	}
</script>